package com.scedu.controller;

import com.scedu.entity.User;
import com.scedu.service.UserService;
import com.scedu.utils.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    //生成验证码
    @GetMapping("/code")
    public  void getVerificationCode(HttpSession httpSession, HttpServletResponse httpServletResponse) throws IOException {
        //1.生成验证码
        String code= VerifyCodeUtil.generateVerifyCode();
        BufferedImage image=VerifyCodeUtil.getBufferedImage(code);
        httpSession.setAttribute("code",code); //存入session作用域中
        //响应图片
        ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
        ImageIO.write(image, "png", servletOutputStream);
    }
    //注册
    @PostMapping("/regsiter")
    public  String regsiter(@Valid User user, BindingResult bindingresult, String code, HttpSession httpSession){
        if (bindingresult.hasErrors()) {
            //有验证错误
            return "redirect:/register"; //跳转到注册界面
        }
        //校验验证码
        String sessioncode=httpSession.getAttribute("code").toString();
        if (sessioncode.equalsIgnoreCase(code)){
            userService.save(user);
            return "redirect:/login"; //跳转到登录界面
        }
        return "redirect:/register"; //跳转到注册界面
    }
    //登录
    @PostMapping("/login")
    public  String login(@RequestParam(value = "username",required = false) String username,
                         @RequestParam(value = "password",required = false) String password,
                         HttpSession httpSession){
        User user=userService.login(username,password);
        if(user!=null){
            httpSession.setAttribute("user", user);
            System.out.println("登录成功！");
            return "redirect:/emp/findAll";
        }
        System.out.println("登录失败！");
        return "redirect:/login"; //跳转到登录界面
    }
}
